const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');
const { Transform } = require('stream');
const fse = require('fs-extra');

// 项目名
const projectName = process.env.VUE_APP_PROJECT_NAME;

// 格式化时间
const formatDate = (date) => {
    const [year, month, day] = [date.getFullYear(), date.getMonth() + 1, date.getDate()].map((num) => num.toString().padStart(2, '0'));
    const [hours, minutes, seconds] = [date.getHours(), date.getMinutes(), date.getSeconds()].map((num) => num.toString().padStart(2, '0'));
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 计算时间差
const calculateSecondsDifference = (endTime, startTime) => {
    const differenceInMs = Math.abs(endTime - startTime);
    const secondsDifference = Math.ceil(differenceInMs / 1000);
    return secondsDifference;
};

// 编译提示语
const success = `✨ SUCCESS ✨ ----- WEBUI编译成功----- ✨ SUCCESS ✨`;
const fail = `❌ FAIL ❌ ----- WEBUI编译失败，请查看构建日志 ----- ❌ FAIL ❌`;
const buildStatus = (status) => {
    console.log(status);
    fs.appendFileSync(logFilePath, `${status}\n`);
};
console.log('✨✨ -----', ` ✔ ✔  选定完成，开始编译   ✔ ✔`, '----- ✨✨');
console.log('✨✨ -----', `编译 WEBUI 为：${projectName ? projectName : '通用版'}`, '----- ✨✨');

// 定制化图片目录
const imgSrcStr = `../src/assets/images`;
const customImgSrcStr = `../src/customImages/${projectName}`;

const imgPath = path.resolve(__dirname, imgSrcStr);
const customImgPath = path.resolve(__dirname, customImgSrcStr);

// 复制定制化图片
if (fs.existsSync(customImgPath)) {
    fse.copy(customImgPath, imgPath, (err) => {
        if (err) throw err;
    });
}

// 构建命令
const buildCommand = 'vue-cli-service build';

// 获取当前时间
const startTime = new Date();
const timestamp = startTime.toISOString().replace(/[-T:.Z]/g, '');

// 构建日志文件路径
const logFileName = `build-${timestamp}.log`;
const logFilePath = path.join(__dirname, logFileName);

// 创建一个新的Transform流，用于将输入数据复制到两个不同的目标
class Duplex extends Transform {
    constructor(destination1, destination2) {
        super();
        this.destination1 = destination1;
        this.destination2 = destination2;
    }
    _transform(chunk, encoding, callback) {
        this.destination1.write(chunk);
        this.destination2.write(chunk);
        callback();
    }
}

// 执行构建命令，并将输出保存到文件和控制台
const buildProcess = exec(buildCommand, (error) => {
    if (error) {
        buildStatus(fail);
    }
});

// 创建用于写入日志文件的可写流
const logStream = fs.createWriteStream(logFilePath, { flags: 'a' }); // 'a' 表示追加到文件末尾

// 创建Duplex流，将构建输出同时发送到文件和控制台
const duplex = new Duplex(process.stdout, logStream);
buildProcess.stdout.pipe(duplex);
buildProcess.stderr.pipe(duplex);

// 构建项目信息
const generateProjectInfo = () => {
    const endTime = new Date();

    // 信息
    const projectInfo = `WEBUI NAME: ${projectName ? projectName : '通用版'}
WEBUI BUILD TIME: ${formatDate(endTime)}
WEBUI COMPILATION DURATION: ${calculateSecondsDifference(endTime, startTime)} second`;

    // 项目信息文件路径
    const logFilePath = path.join(__dirname, '../dist/project.info.log');

    // 写入文件
    fs.writeFileSync(logFilePath, projectInfo);
};

// 当构建完成时关闭日志文件和控制台输出
buildProcess.on('close', (code) => {
    logStream.end();
    if (code === 0) {
        generateProjectInfo();
        buildStatus(success);
    } else {
        buildStatus(fail);
    }
});
